package com.zeratul.common.i18n.web.flux;

import com.zeratul.common.core.utils.I18nUtils;
import com.zeratul.common.i18n.config.prop.I18nProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Locale;

/**
 * WebFlux国际化语言环境处理
 */
@Slf4j
public class WebFluxI18nFilter implements WebFilter, Ordered {

    @Autowired
    private I18nProperties i18NProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String language = exchange.getRequest().getHeaders().getFirst(i18NProperties.getHeaderName());
        Locale locale = I18nUtils.getLocale(language, i18NProperties.getDefaultLanguage());
        LocaleContextHolder.setLocaleContext(new SimpleLocaleContext(locale), true);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
